package com.eimf.saf.common.service.impl;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eimf.saf.base.util.BaseUtil;
import com.eimf.saf.common.dao.AccessLogDao;
import com.eimf.saf.common.entity.AccessLog;
import com.eimf.saf.common.service.AccessLogService;
import com.eimf.saf.security.entity.Staff;
import com.eimf.saf.security.exception.AppException;
import com.eimf.saf.security.util.AppContant;

/**
 * @author eden
 * @date 2013-11-16 上午11:48:24
 * @Description: 操作日志服务类
 */
@Service
public class AccessLogServiceImpl implements AccessLogService
{

    @Autowired
    private AccessLogDao accessLogDao;

    @Override
    public void addPreLog(final HttpServletRequest request)
    {
        try
        {
            final AccessLog log = new AccessLog();
            log.setReqUri(request.getRequestURI());
            log.setReqUrl(request.getRequestURL().toString());
            log.setRemoteAddr(request.getRemoteAddr());
            log.setRemoteHost(request.getRemoteHost());
            log.setContextPath(request.getContextPath());
            log.setServletPath(request.getServletPath());
            log.setReqStTime(BaseUtil.getDateTime());
            log.setStartTime(System.currentTimeMillis());
            log.setSubsystemId("SAF");
            // log.setEmpfId(SAFConfig.getEMPFId());
            final String reqStr = AccessLogServiceImpl.map2String(request.getParameterMap());
            // 处理超长参数
            byte[] bytes = new byte[0];
            if (reqStr != null)
            {
                bytes = reqStr.getBytes("UTF-8");
            }
            if (bytes.length >= 4000)
            {
                final byte[] temp = new byte[4000];
                System.arraycopy(bytes, 0, temp, 0, 4000);
                log.setShortParameters(new String(temp, "UTF-8"));
                log.setLongParameters(bytes);
            }
            // final String logId = accessLogDao.addPreLog(log);
            // log.setLogId(logId);

            request.setAttribute("Filter_AccessLog", log);
        } catch (final Exception e)
        {
            AppException.createErrorException("日志处理转换出错.");
        }

    }

    @Override
    public void updPostLog(final HttpServletRequest request)
    {
        final AccessLog log = (AccessLog) request.getAttribute("Filter_AccessLog");
        if (log == null)
        {
            return;
        }
        final HttpSession session = request.getSession();
        final Staff staff = (Staff) session.getAttribute(AppContant.LOGIN_STAFF_INFO);
        if (null != staff)
        {
            log.setStaffId(staff.getStaffId());
            log.setStaffName(staff.getLoginName());
            final String[] temp = null;// FilterUtils.dealParamCrossFilter(staff.getStaffId(),
            // request.getServletPath(), request);
            if (temp != null)
            {
                log.setResourceKey(temp[1]);
                log.setOperation(temp[2]);
            }
        }
        log.setUsedTime(System.currentTimeMillis() - log.getStartTime());
        // accessLogDao.updPostLog(log);
    }

    private AccessLog transform(final AccessLog accessLog)
    {
        final AccessLog vo = new AccessLog();
        vo.setLogId(accessLog.getLogId());
        vo.setContextPath(accessLog.getContextPath());
        vo.setEmpfId(accessLog.getEmpfId());
        vo.setShortParameters(accessLog.getShortParameters());
        vo.setOperation(accessLog.getOperation());
        vo.setRemoteAddr(accessLog.getRemoteAddr());
        vo.setRemoteHost(accessLog.getRemoteHost());
        vo.setReqStTime(accessLog.getReqStTime());
        vo.setReqUri(accessLog.getReqUri());
        vo.setReqUrl(accessLog.getReqUrl());
        vo.setResourceKey(accessLog.getResourceKey());
        vo.setResult(accessLog.getResult());
        vo.setServletPath(accessLog.getServletPath());
        vo.setStaffId(accessLog.getStaffId());
        vo.setStaffName(accessLog.getStaffName());
        vo.setSubsystemId(accessLog.getSubsystemId());
        vo.setUsedTime(accessLog.getUsedTime());
        return vo;
    }

    private static String map2String(final Map<String, Object> map)
    {
        final StringBuffer sb = new StringBuffer();
        if ((map == null) || (map.size() == 0))
        {
            return sb.toString();
        }
        final Iterator<String> iter = map.keySet().iterator();
        String key = "";
        while (iter.hasNext())
        {
            key = iter.next();
            if (key.toLowerCase().indexOf("password") == -1)
            {
                final String[] values = (String[]) map.get(key);
                sb.append(key).append("=");
                if (values != null)
                {
                    for (int i = 0; i < values.length; i++)
                    {
                        sb.append(values[i]);
                        if (i != values.length - 1)
                        {
                            sb.append(",");
                        }
                    }
                }
                sb.append(";");
            }
        }
        return sb.toString();
    }
}
